<template>
  <div class="dxf-viewer-container" ref="dxfContainer" :style="containerStyle"></div>
</template>

<script>
import { DxfViewer } from 'dxf-viewer'
import * as THREE from 'three'
import mainFont from "@/assets/fonts/Roboto-LightItalic.ttf"
import aux1Font from "@/assets/fonts/NotoSansDisplay-SemiCondensedLightItalic.ttf"
import aux2Font from "@/assets/fonts/HanaMinA.ttf"
import aux3Font from "@/assets/fonts/NanumGothic-Regular.ttf"

export default {
  name: 'DxfViewerComponent',
  props: {
    dxfUrl: {
      type: String,
      required: true
    },
    height: {
      type: String,
      default: '800px'
    },
    backgroundColor: {
      type: String,
      default: '#ffffff'
    },
    initialZoom: {
      type: Number,
      default: 1.0
    },
    fitMargin: {
      type: Number,
      default: 10
    }
  },
  computed: {
    containerStyle() {
      return {
        height: this.height
      }
    }
  },
  data() {
    return {
      viewer: null
    }
  },
  mounted() {
    this.initDxfViewer()
  },
  beforeDestroy() {
    if (this.viewer) {
      this.viewer.Destroy()
    }
  },
  watch: {
    dxfUrl: {
      handler(newUrl) {
        if (this.viewer && newUrl) {
          this.loadDxf()
        }
      }
    }
  },
  methods: {
    initDxfViewer() {
      try {
        this.viewer = new DxfViewer(this.$refs.dxfContainer, {
          clearColor: new THREE.Color(this.backgroundColor),
          autoResize: true,
          colorCorrection: true,
          sceneOptions: {
            wireframeMesh: true
          }
        })

        this.loadDxf()
      } catch (error) {
        console.error('初始化DXF查看器失败:', error)
        this.$message.error('初始化DXF查看器失败')
      }
    },
    async loadDxf() {
      try {
        await this.viewer.Load({
          url: this.dxfUrl,
          fonts: [mainFont, aux1Font, aux2Font, aux3Font],
          progressCbk: (phase, processed, total) => {
            this.$emit('loading-progress', { phase, processed, total })
            console.log(`Loading phase: ${phase}, Progress: ${processed}/${total}`)
          },
          workerFactory: null
        })

        const bounds = this.viewer.GetBounds()
        if (bounds) {
          const adjustedMargin = this.fitMargin / this.initialZoom
          this.viewer.FitView(bounds.minX, bounds.maxX, bounds.minY, bounds.maxY, adjustedMargin)
        }

        for (const layer of this.viewer.GetLayers()) {
          this.viewer.ShowLayer(layer.name, true)
        }

        this.$emit('load-success')
      } catch (error) {
        console.error('加载DXF文件失败:', error)
        this.$message.error('加载DXF文件失败')
        this.$emit('load-error', error)
      }
    }
  }
}
</script>

<style scoped>
.dxf-viewer-container {
  width: 100%;
}
</style> 